package com.example.lvzhaobing.bluetoothgallery;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import app.akexorcist.bluetotohspp.library.BluetoothSPP;
import app.akexorcist.bluetotohspp.library.BluetoothState;
import app.akexorcist.bluetotohspp.library.DeviceList;

public class MainActivity extends AppCompatActivity {

    BluetoothSPP bt = new BluetoothSPP(this);
    public static final String IMAGE_UNSPECIFIED = "image/*";//随意图片类型
    public static final int PHOTOCUT=1;//裁剪
    public static final int PHOTORESOULT = 2;// 结果
    public static final int PICTURE_WIDTH = 1024;
    public static final int PICTURE_HEIGHT = 768;
    private ImageView imageView;
    private Uri source_uri;
    private Uri image_uri;
    private String source_path;
    private String image_path;
    private Bitmap send_image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.imageView = findViewById(R.id.imageView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(!bt.isBluetoothAvailable()) {
            Toast.makeText(this,"蓝牙不可用",Toast.LENGTH_SHORT).show();
        }
        if(!bt.isBluetoothEnabled()){
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT);
        }
        else {
            if(!bt.isServiceAvailable()) {
                bt.setupService();
                bt.startService(BluetoothState.DEVICE_OTHER);
            }
            bt.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
                public void onDeviceConnected(String name, String address) {
                    // Do something when successfully connected
                    Log.e("onDeviceConnected","Device Connected");
                }

                public void onDeviceDisconnected() {
                    // Do something when connection was disconnected
                    Log.e("onDeviceConnected","Device DisConnected");
                }

                public void onDeviceConnectionFailed() {
                    // Do something when connection failed
                    Log.e("onDeviceConnected","Device Connected Faild");
                }
            });
        }
    }

    public void onButtonClick(View view){
        switch (view.getId())
        {
            case R.id.openButton: {
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10);
                }
                // 调用系统的相冊
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        IMAGE_UNSPECIFIED);
                // 返回后显示图片
                startActivityForResult(intent, PHOTORESOULT);
            }
            break;
            case R.id.connectButton:{
                bt.disconnect();
                Intent intent = new Intent(getApplicationContext(), DeviceList.class);
                intent.putExtra("bluetooth_devices", "Bluetooth devices");
                intent.putExtra("no_devices_found", "No device");
                intent.putExtra("scanning", "Scanning");
                intent.putExtra("scan_for_devices", "Search");
                intent.putExtra("select_device", "Select");
                startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
            }break;
            case R.id.sendButton:{
                //获取到Bitmap对应的RGB数据
                byte[] datas = bitmap2RGB(this.send_image);
                //存储文件
                createFileWithByte(datas,"BitmapData.dat");
                //byte[] data1 = {'{','{','{','{','{','{','{','{'};
                //byte[] data2 = {'}','}','}','}','}','}','}','}'};
                //bt.send(data1,false);
                bt.send(datas, false);
                //bt.send(data2,false);
            } break;
            case R.id.deleteButton:{
                deleteImage(source_path,source_uri);
                deleteImage(image_path,image_uri);
            }
            break;
            default:break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTORESOULT:{
                if(this.image_uri!=null) {
                    Log.e("image_uri", image_uri.toString());
                    ContentResolver cr = this.getContentResolver();
                    try{
                        //获取原图
                        Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(image_uri));
                        //截取图片中间部分
                        this.send_image = ThumbnailUtils.extractThumbnail(bitmap,PICTURE_WIDTH,PICTURE_HEIGHT);
                        /* 将Bitmap设定到ImageView */
                        this.imageView.setImageBitmap(send_image);
                    }
                    catch (FileNotFoundException e){
                        Log.e("Exception", e.getMessage(),e);
                    }
                }
            }
            case PHOTOCUT:{
                Uri uri = data.getData();
                if(uri != null) {
                    source_uri = uri;
                    Log.e("uri", source_uri.toString());
                    this.source_path = getRealFilePath(source_uri);
                    ContentResolver cr = this.getContentResolver();
                    cropRawPhoto(source_uri);
                }
            }
            default:break;
        }
        if(requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
            if(resultCode == Activity.RESULT_OK)
                bt.connect(data);
        } else if(requestCode == BluetoothState.REQUEST_ENABLE_BT) {
            if(resultCode == Activity.RESULT_OK) {
                bt.setupService();
                bt.startService(BluetoothState.DEVICE_OTHER);
            } else {
                // Do something if user doesn't choose any device (Pressed back)
            }
        }

    }

    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //把裁剪的数据填入里面
        intent.putExtra("crop", "true");
        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", PICTURE_WIDTH);
        intent.putExtra("aspectY", PICTURE_HEIGHT);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", PICTURE_WIDTH);
        intent.putExtra("outputY", PICTURE_HEIGHT);
        intent.putExtra("return-data", true);
        //裁剪后的图片Uri路径，uritempFile为Uri类变量
        Uri uritempFile = Uri.parse("file://" + "/" + Environment.getExternalStorageDirectory().getPath() + "/" + "small.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uritempFile);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        this.image_uri = uritempFile;
        this.image_path = getRealFilePath(this.image_uri);
        startActivityForResult(intent, PHOTORESOULT);
    }
    /**
     * delete image
     *
     * @param fileName filename
     * @param fileUri  file uri
     */
    private void deleteImage(String fileName, Uri fileUri) {
        File file = new File(fileName);
        if (file.exists() && fileUri!=null) {
            file.delete();
            Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            ContentResolver mContentResolver = this.getContentResolver();
            String where = MediaStore.Images.Media.DATA + "='" + fileName + "'";
            // 删除操作
            mContentResolver.delete(uri, where, null);
            //发送广播
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(fileUri);
            this.sendBroadcast(intent);
        }
    }
    /**
     * android 4.4 获取 uri 真实路径
     *
     * @param uri uri
     * @return /sdcard/0/xx.jpg
     */
    public String getRealFilePath(Uri uri) {
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = this.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
            * @方法描述 Bitmap转RGB
     */
    public static byte[] bitmap2RGB(Bitmap bitmap) {
        int bytes = bitmap.getByteCount();  //返回可用于储存此位图像素的最小字节数
        ByteBuffer buffer = ByteBuffer.allocate(bytes); //  使用allocate()静态方法创建字节缓冲区
        bitmap.copyPixelsToBuffer(buffer); // 将位图的像素复制到指定的缓冲区
        byte[] rgba = buffer.array();
        byte[] pixels = new byte[(rgba.length / 4) * 2];
        int count = rgba.length / 4;
        //Bitmap像素点的色彩通道排列顺序是RGBA
        for (int i = 0; i < count; i++) {
            byte r = (byte)(rgba[i*4]>>3);
            byte g = (byte)(rgba[i*4+1]>>2);
            byte b = (byte)(rgba[i*4+2]>>3);
            pixels[i*2] = (byte)((r<<3)+((g&0x38)>>3));
            pixels[i*2+1] = (byte)(((g&0x07)<<5)+b);
        }
        return pixels;
    }

    /**
     * 根据byte数组生成文件
     *
     * @param bytes
     *            生成文件用到的byte数组
     */
    private void createFileWithByte(byte[] bytes,String fileName) {
        // TODO Auto-generated method stub
        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        File file = new File(Environment.getExternalStorageDirectory(),
                fileName);
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件存在则删除
            if (file.exists()) {
                file.delete();
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(bytes);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
    }

}
